﻿using DKPScoreWebApi.Data;
using DKPScoreWebApi.DTOs.Requests;
using DKPScoreWebApi.DTOs.Results;
using DKPScoreWebApi.Models;
using DKPScoreWebApi.Services.Interfaces;
using Microsoft.EntityFrameworkCore;

namespace DKPScoreWebApi.Services.Implementations
{
    /// <summary>
    /// 工会管理服务实现
    /// 处理工会相关的业务逻辑
    /// </summary>
    public class GuildService : IGuildService
    {
        private readonly AppDbContext _context;
        private readonly ILogger<GuildService> _logger;

        /// <summary>
        /// 构造函数，依赖注入数据库上下文和日志服务
        /// </summary>
        /// <param name="context">数据库上下文</param>
        /// <param name="logger">日志服务</param>
        public GuildService(AppDbContext context, ILogger<GuildService> logger)
        {
            _context = context;
            _logger = logger;
        }

        /// <summary>
        /// 创建新工会
        /// </summary>
        public async Task<Guild> CreateGuildAsync(int userId, CreateGuildRequest request)
        {
            // 创建工会实体
            var guild = new Guild
            {
                Name = request.Name,
                Description = request.Description,
                GameType = request.GameType,
                CreatedBy = userId,
                CreatedAt = DateTime.Now
            };

            // 保存工会到数据库
            _context.Guilds.Add(guild);
            await _context.SaveChangesAsync();

            // 将创建者添加为工会所有者
            var admin = new GuildAdmin
            {
                GuildId = guild.Id,
                UserId = userId,
                Role = "owner", // 所有者角色
                AddedBy = userId,
                AddedAt = DateTime.Now
            };

            _context.GuildAdmins.Add(admin);
            await _context.SaveChangesAsync();

            // 记录日志
            _logger.LogInformation("用户 {UserId} 创建工会 {GuildName}", userId, request.Name);
            return guild;
        }

        /// <summary>
        /// 获取用户管理的所有工会
        /// </summary>
        public async Task<List<Guild>> GetUserGuildsAsync(int userId)
        {
            // 查询用户有管理权限的所有工会
            return await _context.GuildAdmins
                .Where(ga => ga.UserId == userId)
                .Include(ga => ga.Guild)
                .ThenInclude(g => g.Members.Where(m => m.IsActive)) // 包含活跃成员
                .Select(ga => ga.Guild)
                .OrderBy(g => g.Name) // 按名称排序
                .ToListAsync();
        }

        /// <summary>
        /// 根据ID获取工会详情
        /// </summary>
        public async Task<Guild> GetGuildByIdAsync(int guildId)
        {
            // 查询工会详情，包含成员和积分项目
            return await _context.Guilds
                .Include(g => g.Members.Where(m => m.IsActive))
                .Include(g => g.PointItems.Where(pi => pi.IsActive))
                .FirstOrDefaultAsync(g => g.Id == guildId);
        }

        /// <summary>
        /// 检查用户是否有指定工会的管理权限
        /// </summary>
        public async Task<bool> IsUserGuildAdminAsync(int userId, int guildId)
        {
            // 查询用户是否在工会管理员列表中
            return await _context.GuildAdmins
                .AnyAsync(ga => ga.UserId == userId && ga.GuildId == guildId);
        }

        /// <summary>
        /// 添加工会管理员
        /// </summary>
        public async Task<bool> AddGuildAdminAsync(int guildId, int targetUserId, string role, int addedBy)
        {
            // 检查是否已经是管理员
            var existing = await _context.GuildAdmins
                .FirstOrDefaultAsync(ga => ga.GuildId == guildId && ga.UserId == targetUserId);

            if (existing != null)
                return false; // 已经是管理员，添加失败

            // 创建新的管理员记录
            var admin = new GuildAdmin
            {
                GuildId = guildId,
                UserId = targetUserId,
                Role = role,
                AddedBy = addedBy,
                AddedAt = DateTime.Now
            };

            _context.GuildAdmins.Add(admin);
            await _context.SaveChangesAsync();

            return true;
        }

        /// <summary>
        /// 获取工会统计信息
        /// </summary>
        public async Task<GuildStats> GetGuildStatsAsync(int guildId)
        {
            var stats = new GuildStats();

            // 成员统计：查询工会所有成员
            var members = await _context.GuildMembers
                .Where(m => m.GuildId == guildId)
                .ToListAsync();

            stats.TotalMembers = members.Count;
            stats.ActiveMembers = members.Count(m => m.IsActive);

            // 积分统计：查询工会所有积分记录
            var records = await _context.PointRecords
                .Where(pr => pr.GuildId == guildId)
                .ToListAsync();

            // 计算总积分
            stats.TotalPointsAwarded = records.Sum(r => r.PointsEarned);

            // 计算时间范围内的积分
            var today = DateTime.Today;
            var weekStart = today.AddDays(-(int)today.DayOfWeek + 1); // 本周一开始
            var monthStart = new DateTime(today.Year, today.Month, 1); // 本月1号

            stats.TodayPointsAwarded = records
                .Where(r => r.CreatedAt.Date == today)
                .Sum(r => r.PointsEarned);

            stats.ThisWeekPointsAwarded = records
                .Where(r => r.CreatedAt >= weekStart)
                .Sum(r => r.PointsEarned);

            stats.ThisMonthPointsAwarded = records
                .Where(r => r.CreatedAt >= monthStart)
                .Sum(r => r.PointsEarned);

            // 职业分布统计
            stats.ClassDistribution = members
                .Where(m => m.IsActive && !string.IsNullOrEmpty(m.CharacterClass))
                .GroupBy(m => m.CharacterClass)
                .ToDictionary(g => g.Key, g => g.Count());

            // 最近活动：查询最近10条积分记录
            var recentRecords = await _context.PointRecords
                .Where(pr => pr.GuildId == guildId)
                .Include(pr => pr.Member)
                .Include(pr => pr.PointItem)
                .OrderByDescending(pr => pr.CreatedAt)
                .Take(10)
                .ToListAsync();

            // 转换为活动记录格式
            stats.RecentActivities = recentRecords.Select(r => new RecentActivity
            {
                MemberId = r.MemberId,
                MemberName = r.Member.Name,
                Action = r.Description,
                Points = r.PointsEarned,
                CreatedAt = r.CreatedAt
            }).ToList();

            return stats;
        }

        /// <summary>
        /// 更新工会信息
        /// </summary>
        public async Task<bool> UpdateGuildAsync(int guildId, CreateGuildRequest request)
        {
            // 查找工会
            var guild = await _context.Guilds.FindAsync(guildId);
            if (guild == null)
                return false;

            // 更新工会信息
            guild.Name = request.Name;
            guild.Description = request.Description;
            guild.GameType = request.GameType;

            await _context.SaveChangesAsync();
            return true;
        }

        /// <summary>
        /// 删除工会（软删除）
        /// </summary>
        public async Task<bool> DeleteGuildAsync(int guildId)
        {
            var guild = await _context.Guilds.FindAsync(guildId);
            if (guild == null)
                return false;

            // 软删除：标记为不活跃，而不是物理删除
            guild.IsActive = false;
            await _context.SaveChangesAsync();

            return true;
        }
    }
}
